package test.my_argumentResolver;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import test.annotation.AuthParam;
import test.annotation.Whitelist;
import test.domin.User;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/6/24 20:55
 * @ Description:
 */
@Component
public class AuthParamResolver implements HandlerMethodArgumentResolver {

    /*
    * 用于判定是否需要处理该参数分解，返回true为需要，并会去调用下面的方法resolveArgument。
    * */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class) && parameter.hasParameterAnnotation(AuthParam.class);
    }

    /*
    * 真正用于处理参数分解的方法，返回的Object就是controller方法上的形参对象（反过来可以在此处修改参数值）。
    * */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        User currentUser = new User();
        if(User.class != parameter.getParameterType()){
            System.out.println("入参用户类型不正确！");
            return null;
        }
        Class<?> parameterType = parameter.getParameterType();
        System.out.println("参数类型------" + parameterType);
        String name = parameter.getParameter().getName();
        System.out.println("参数名称------" + name);
        int parameterIndex = parameter.getParameterIndex();
        System.out.println("参数索引-------" + parameterIndex);
        /*mavContainer.setIgnoreDefaultModelOnRedirect(false);
        mavContainer.setViewName("anon");
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("viewName" , "anon");
        mavContainer.setRedirectModel(modelMap);*/
        Whitelist whitelist = parameter.getMethodAnnotation(Whitelist.class);
        // 通过 webRequest 和 whitelist 校验白名单

        // 请求header中有Authorization的值表示token，根据token解析出当前用户的信息
        HttpServletRequest httpServletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = httpServletRequest.getHeader("Authorization");
        // 如下模拟token的解析过程
        if("123".equals(token)){
            currentUser.setName("XuLeHuang");
            currentUser.setSex("male");
            currentUser.setAge(12);
        }
        return currentUser;

    }
}
